#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/queue.h>
#include "common.h"

struct TVTS_SLL_ENTRY {
	char* data;
	SLIST_ENTRY(TVTS_SLL_ENTRY) entries;
};

SLIST_HEAD(TVTS_SLL_HEAD, TVTS_SLL_ENTRY);

int main(int argc, char* argv[]) {
	char buf[MAXLINE];

	// SLL
	struct TVTS_SLL_ENTRY *np = 0;
	struct TVTS_SLL_HEAD head;
	SLIST_INIT(&head);

	// insert
	printf("Start insertion ...\n");
	int i;
	for (i = 1; i < argc; i ++) {
		char* arg = argv[i];
		snprintf(buf, MAXLINE, "%s-%d-%s", arg, i, arg);
		char* arg_cp = cp_str(buf);
		printf("> %d: %s => %s\n", i, arg, arg_cp);

		np = malloc(sizeof(struct TVTS_SLL_ENTRY));
		np->data = arg_cp;
		SLIST_INSERT_HEAD(&head, np, entries);
	}
	printf("Insertions done.\n");

	// iterate
	printf("Start iteration ...\n");
	i = 0;
	SLIST_FOREACH(np, &head, entries) {
    	printf("%d: %s\n", ++i, np->data);
	}
	printf("Iteration done.\n");

	// destruct
	printf("Cleaning ...\n");
	while (!SLIST_EMPTY(&head)) {           /* List deletion */
	   np = SLIST_FIRST(&head);
	   SLIST_REMOVE_HEAD(&head, entries);
	   free(np->data);
	   free(np);
    }
    SLIST_INIT(&head);
    printf("Cleaning done.\n");
}
